<template>
  <el-dialog @close="close" v-model="dialogVisible" :title="title" width="50%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px">
      <el-form-item label="设备平台" prop="type_id">
        <el-select v-model="ruleForm.type_id" placeholder="请选择" style="width: 100%">
          <el-option v-for="item in typeArr" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入设备名称" />
      </el-form-item>
      <el-form-item label="前缀标识" prop="pix" v-if="!ruleForm.id">
        <el-input v-model="ruleForm.pix" placeholder="请输入前缀标识" />
      </el-form-item>
      <el-form-item label="设备编号" prop="sn">
        <el-input v-model="ruleForm.sn" placeholder="请输入设备编号" />
      </el-form-item>
      <el-form-item label="额定功率" prop="power">
        <el-input v-model="ruleForm.power" placeholder="请输入额定功率">
          <template #append>瓦（W）</template>
        </el-input>
      </el-form-item>
      <el-form-item label="预警功率" prop="power">
        <el-input v-model="ruleForm.powerthreshold" placeholder="请输入预警功率">
          <template #append>瓦（W）</template>
        </el-input>
      </el-form-item>
      <el-form-item label="医院" prop="platform_id">
        <el-select
          v-model="ruleForm.platform_id"
          placeholder="请选择"
          filterable
          style="width: 100%"
          @change="handlePlatChange"
        >
          <el-option v-for="item in platData" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="房间" prop="room_id" v-show="ruleForm.platform_id">
        <el-select v-model="ruleForm.room_id" placeholder="请选择" filterable style="width: 100%">
          <el-option v-for="item in roomData" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="ruleForm.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="自动开关时间" prop="config">
        <el-row
          :gutter="20"
          v-for="(item, index) in ruleForm.config.autoTime"
          :key="index"
          style="margin-bottom: 10px"
        >
          <el-col :span="8">
            <!-- <el-time-picker
              v-model="item.openTime"
              format="HH:mm"
              placeholder="开启时间"
              style="width: 100%"
            /> -->
            <el-time-select
              v-model="item.openTime"
              start="00:00"
              step="00:05"
              end="23:55"
              placeholder="开启时间"
              format="HH:mm:ss"
            />
          </el-col>
          <el-col :span="8">
            <!-- <el-time-picker
              v-model="item.closeTime"
              format="HH:mm"
              placeholder="关闭时间"
              style="width: 100%"
            /> -->
            <el-time-select
              v-model="item.closeTime"
              start="00:00"
              step="00:05"
              end="23:55"
              placeholder="关闭时间"
              format="HH:mm:ss"
            />
          </el-col>
          <el-col :span="8">
            <div style="text-align: right">
              <el-button type="primary" @click="addAutoTime" v-if="index == 0">新增</el-button>
              <el-button type="danger" @click="delAutoTime(index)" v-if="index > 0">删除</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saveLoading" @click="handleConfim(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ElMessageBox, ElMessage, FormInstance, ElNotification } from 'element-plus'
import { reactive, ref } from 'vue'
import { deptData } from '@/mock/system'
import { addEquipInfo, editEquipInfo, platformList, roomList } from '@/api/admin'
import { useRoute } from 'vue-router'
const route = useRoute()
const ruleFormRef = ref<FormInstance>()
const dialogVisible = ref<boolean>(false)
const deptDataOptions = ref(deptData)
const title = ref('新增设备')
const checkIsPositive = (rule, value, callback) => {
  if (!value) {
    callback()
  } else {
    const reg = /^\d+(?=\.{0,1}\d+$|$)/
    if (reg.test(value)) {
      callback()
    } else {
      callback(new Error('请输入大于等于0的正数'))
    }
  }
}
const rules = reactive({
  type_id: [{ required: true, message: '请选择设备平台', trigger: 'change' }],
  name: [{ required: true, message: '请输入设备名称', trigger: 'blur' }],
  // pix: [{ required: true, message: '请输入前缀标识', trigger: 'blur' }],
  power: [{ validator: checkIsPositive, trigger: 'blur' }],
  // platform_id: [{ required: true, message: '请选择医院', trigger: 'change' }],
  // room_id: [{ required: true, message: '请选择医院', trigger: 'change' }],
})
const ruleForm = reactive({
  id: '',
  name: '',
  pix: '',
  sn: '',
  platform_id: '',
  type_id: Number(route.query.id) || '',
  status: 1,
  room_id: '',
  remark: '',
  power: '',
  config: {
    autoTime: [
      {
        openTime: '',
        closeTime: '',
      },
    ],
  },
})
const saveLoading = ref(false)
const emit = defineEmits(['refresh'])
const platData = ref()
const roomData = ref()
const props = defineProps({
  typeArr: {
    type: Array,
    default: [],
  },
})

function close() {
  ruleFormRef.value.resetFields()
  Object.keys(ruleForm).forEach((key) => {
    if (key == 'status') ruleForm[key] = 1
    else if (key == 'type_id') ruleForm[key] = Number(route.query.id) || ''
    else if (key == 'config')
      ruleForm[key] = {
        autoTime: [
          {
            openTime: '',
            closeTime: '',
          },
        ],
      }
    else ruleForm[key] = null
  })
}

const show = (item = {}) => {
  title.value = '新增设备'
  if (item.id) {
    title.value = '编辑设备'
    Object.keys(ruleForm).forEach((key) => {
      if (key == 'config') {
        if (item[key]) {
          ruleForm[key] = item[key]
        }
      } else ruleForm[key] = item[key]
    })
    getRoomList(ruleForm.platform_id)
  }
  dialogVisible.value = true
  getPlatList()
}
//医院
const getPlatList = () => {
  platformList({ selectFields: 'id,name' }).then((res) => {
    if (res.code == 200) {
      platData.value = res.data
    }
  })
}
const handlePlatChange = (val) => {
  getRoomList(val)
}
//房间列表
const getRoomList = (id) => {
  let filter = JSON.stringify({ platform_id: id })
  roomList({ selectFields: 'id,name', filter: filter }).then((res) => {
    if (res.code == 200) {
      roomData.value = res.data
    }
  })
}

const handleConfim = async (done: () => void) => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      saveLoading.value = true
      if (ruleForm.id) {
        //编辑
        editEquipInfo(ruleForm).then((res) => {
          if (res.code == 200) {
            ElNotification({
              title: '编辑成功',
              message: res.msg,
              type: 'success',
            })
            emit('refresh')
          }
          dialogVisible.value = false
          saveLoading.value = false
        })
      } else {
        //新增
        addEquipInfo(ruleForm).then((res) => {
          if (res.code == 200) {
            ElNotification({
              title: '添加成功',
              message: res.msg,
              type: 'success',
            })
            emit('refresh')
          }
          dialogVisible.value = false
          saveLoading.value = false
        })
      }
    }
  })
}

const addAutoTime = () => {
  let length = ruleForm.config.autoTime.length
  if (!ruleForm.config.autoTime[length - 1].openTime) {
    ElMessage.warning('请选择开启时间！')
    return
  }
  if (!ruleForm.config.autoTime[length - 1].closeTime) {
    ElMessage.warning('请选择关闭时间！')
    return
  }
  ruleForm.config.autoTime.push({
    openTime: '',
    closeTime: '',
  })
}

const delAutoTime = (index) => {
  ruleForm.config.autoTime.splice(index, 1)
}

defineExpose({
  show,
})
</script>
<style lang="scss" scoped></style>
